using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MEA.AE_Data;
using MEA.AE_Data.Config;
using MEA.Chart;

namespace MEA.AE_BusinessLogic
{
	public class UIGraphLiveView : UIGraphBase
	{
		private EventHandler ev_ExportButtonPressed;

		public event EventHandler ev_RecordButtonPressed;

		public event EventHandler<UIGraphWindowListNr> ev_StopButtonPressed;

		public UIGraphLiveView(ConfigBase.EGraphicAspect graphicaspect)
			: base(graphicaspect)
		{
			initCheckedDataGridViewGraphSignals();
			graphicAspect = graphicaspect;
			toolStripButtonRecord.Click += toolStripButtonRecord_Click;
			toolStripButtonRecord.Visible = true;
			toolStripButtonStop.Click += toolStripButtonStop_Click;
			toolStripButtonStop.Visible = true;
			toolStripButtonExport.Visible = false;
			toolStripButtonExport.Enabled = false;
			toolStripButtonExport.Click += base.toolDataLogStripButtonExport_Click;
			tend = 100f;
			toolStripComboBoxStep.Items.Clear();
			toolStripComboBoxStep.Items.AddRange(new object[4] { "0.1", "1", "5", "10" });
			toolStripComboBoxStep.SelectedIndex = 0;
			if (graphicAspect == ConfigBase.EGraphicAspect.eShowGraphLiveView)
			{
				hScrollBar1.Enabled = false;
				toolStripButtonFileInfo.Available = false;
			}
		}

		public override void UpdateData(object sender, EventArgs e)
		{
			List<string> list = new List<string>();
			if (functs != null)
			{
				int count;
				lock (functs)
				{
					count = functs.Count;
				}
				for (int i = 0; i < count; i++)
				{
					Var var = (Var)base.GraphVars[i];
					lock (functs.SyncRoot)
					{
						Function function = (Function)functs[i];
						PointF pointF = default(PointF);
						if (var.data.Count > 0)
						{
							pointF = var.data[var.data.Count - 1];
							if (var.data.Count != function.points.Count)
							{
								function.AddPoint(ref pointF);
								if (var.data.Count == var.timestamps.Count)
								{
									function.timestamps.Add(var.timestamps[var.data.Count - 1]);
								}
								function.DrawLastAddedPoint(graph.g);
							}
							if (graphicAspect == ConfigBase.EGraphicAspect.eShowGraphLiveView)
							{
								lock (list)
								{
									switch (var.Format)
									{
									case ConfigBase.EStringFormat.e_X1:
									case ConfigBase.EStringFormat.e_X2:
									case ConfigBase.EStringFormat.e_X4:
									case ConfigBase.EStringFormat.e_X8:
										list.Add(string.Format("{0} {1}\r\n", string.Format(ConfigBase.StrStringFormat[(uint)var.Format], (int)pointF.Y), ConfigLiveView.SigClass[(int)var.SigClass].Unit));
										break;
									case ConfigBase.EStringFormat.e_F0:
									case ConfigBase.EStringFormat.e_F1:
									case ConfigBase.EStringFormat.e_F2:
									case ConfigBase.EStringFormat.e_F3:
										list.Add(string.Format("{0} {1}\r\n", string.Format(ConfigBase.StrStringFormat[(uint)var.Format], pointF.Y), ConfigLiveView.SigClass[(int)var.SigClass].Unit));
										break;
									case ConfigBase.EStringFormat.e_Bin:
										list.Add(string.Format("{0} {1}\r\n", string.Format(ConfigBase.StrStringFormat[(uint)var.Format], (int)pointF.Y), ConfigLiveView.SigClass[(int)var.SigClass].Unit));
										break;
									default:
										list.Add(string.Format("{0} {1}\r\n", string.Format("{0:F2}", (int)pointF.Y), ConfigLiveView.SigClass[(int)var.SigClass].Unit));
										break;
									}
								}
								if (function.AB == ConfigData.e_ECUS.ECU_A)
								{
									if (CaCrDisplayA != null)
									{
										if (function.Ecu_Emessage == ConfigLiveView.ESignals.e_CAN_Prpl_nPrpl)
										{
											if (function.points.Count > CaCrDisplayA.PosOfCaCrDispfLiveView.Count)
											{
												CaCrDisplayA.addToPosOfCaCrDispfLiveView(pointF);
											}
										}
										else if (function.Ecu_Emessage == ConfigLiveView.ESignals.e_CaSCrS_phiDiff)
										{
											CaCrDisplayA.addYValToCaCr(pointF, ref graph.g, ref function.koordsyst, function.Visible);
										}
									}
								}
								else if (CaCrDisplayB != null)
								{
									if (function.Ecu_Emessage == ConfigLiveView.ESignals.e_CAN_Prpl_nPrpl)
									{
										if (function.points.Count > CaCrDisplayB.PosOfCaCrDispfLiveView.Count)
										{
											CaCrDisplayB.addToPosOfCaCrDispfLiveView(pointF);
										}
									}
									else if (function.Ecu_Emessage == ConfigLiveView.ESignals.e_CaSCrS_phiDiff)
									{
										CaCrDisplayB.addYValToCaCr(pointF, ref graph.g, ref function.koordsyst, function.Visible);
									}
								}
							}
						}
					}
					if (i == 0)
					{
						setScrollbarRange();
					}
				}
			}
			if (checkedDataGridViewGraphSignals.RowCount > 0)
			{
				CheckGraphMove();
				if (graphicAspect == ConfigBase.EGraphicAspect.eShowGraphLiveView)
				{
					UpdateLiveViewCurrentValue_Textbox(list);
					pictBox1.Invalidate();
				}
			}
		}

		private void CheckGraphMove()
		{
			try
			{
				if (functs.Count <= 0 || koordsysts.Count <= 0)
				{
					return;
				}
				lock (functs[0])
				{
					Function function = (Function)functs[0];
					if (!(function.lastaddedpoint.X > ((Koordsyst)koordsysts[0]).XMax))
					{
						return;
					}
					float length = 1f;
					foreach (Koordsyst koordsyst3 in koordsysts)
					{
						length = koordsyst3.XLen;
						koordsyst3.XMin += length * 9f / 10f;
						koordsyst3.XMax += length * 9f / 10f;
					}
					Invoke((MethodInvoker)delegate
					{
						try
						{
							hScrollBar1.Value += (int)(length * 9f) / 10;
						}
						catch
						{
						}
					});
					setScrollbarRange();
					RedrawAll(true);
				}
			}
			catch (Exception)
			{
				lock (koordsysts)
				{
					foreach (Koordsyst koordsyst4 in koordsysts)
					{
						float xLen = koordsyst4.XLen;
						koordsyst4.XMin = 0f;
						koordsyst4.XMax = ((Function)functs[0]).lastaddedpoint.X;
					}
					Invoke((MethodInvoker)delegate
					{
						try
						{
							hScrollBar1.Minimum = 0;
							hScrollBar1.Maximum = (int)((Koordsyst)koordsysts[0]).XMax;
							hScrollBar1.Value = (int)((Koordsyst)koordsysts[0]).XMax;
						}
						catch
						{
						}
					});
				}
			}
		}

		public void UpdateLiveViewCurrentValue_Textbox(List<string> values)
		{
			CheckedSigVals vals;
			string str;
			Invoke((MethodInvoker)delegate
			{
				if (checkedSigIx.Count == values.Count)
				{
					for (int i = 0; i < values.Count; i++)
					{
						vals = checkedSigIx[i];
						str = values[i];
						if (str != vals.sigVal)
						{
							vals.sigVal = str;
							checkedSigIx[i] = vals;
							checkedDataGridViewGraphSignals.Rows[i].Cells[2].Value = str;
						}
					}
				}
			});
		}

		protected override void setScrollbarRange()
		{
			if (hScrollBar1.InvokeRequired)
			{
				dbg_setscroll method = setScrollbarRange;
				Invoke(method, new object[0]);
				return;
			}
			lock (functs.SyncRoot)
			{
				Function function = (Function)functs[0];
				xmin = 0;
				xmax = 10;
				if (function.points.Count > 1)
				{
					PointF pointF = function.points[0];
					PointF pointF2 = function.points[function.points.Count - 1];
					xmin = (int)pointF.X;
					xmax = (int)pointF2.X;
				}
				lock (hScrollBar1)
				{
					if (xmin < hScrollBar1.Minimum)
					{
						hScrollBar1.Minimum = xmin;
					}
					if (xmax > hScrollBar1.Maximum)
					{
						hScrollBar1.Maximum = xmax + 10;
					}
				}
			}
		}

		public void ClearAllPoints(object sender, EventArgs e)
		{
			lock (functs.SyncRoot)
			{
				foreach (Function funct in functs)
				{
					funct.points.Clear();
				}
			}
			lock (base.GraphVars.SyncRoot)
			{
				foreach (Var graphVar in base.GraphVars)
				{
					graphVar.data.Clear();
				}
			}
		}

		private void toolStripButtonRecord_Click(object sender, EventArgs e)
		{
			try
			{
				string text = ConfigData.LogRootPath + "\\LiveView";
				Directory.CreateDirectory(text);
				SaveFileDialog saveFileDialog = new SaveFileDialog();
				saveFileDialog.Filter = "Wizard files (*.ae3)|*.ae3|All files (*.*)|*.*";
				saveFileDialog.FilterIndex = 1;
				saveFileDialog.InitialDirectory = text;
				saveFileDialog.FileName = "LiveView_" + DateTime.UtcNow.ToString("yyyyMMdd");
				if (saveFileDialog.ShowDialog() == DialogResult.OK)
				{
					base.MyFileName = saveFileDialog.FileName;
					if (this.ev_RecordButtonPressed != null)
					{
						this.ev_RecordButtonPressed(this, e);
					}
					toolStripButtonRecord.Enabled = false;
					toolStripButtonExport.Enabled = false;
					toolStripButtonShiftEnabled(false);
					toolStripButtonFileInfo.Enabled = false;
					toolStripButtonFileInfo.Available = false;
					toolStripButtonStop.Enabled = false;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("Warning: Live View recording failed!\n" + ex.Message, ConfigData.WizardSwName);
			}
		}

		private void toolStripButtonStop_Click(object sender, EventArgs e)
		{
			toolStripButtonRecordEnabled(true);
			toolStripButtonStopEnabled(false);
			int myListNr2 = myListNr;
			if (this.ev_StopButtonPressed != null)
			{
				this.ev_StopButtonPressed(sender, new UIGraphWindowListNr(myListNr));
			}
		}

		public void toolStripButtonRecordEnabled(bool enable)
		{
			Invoke((MethodInvoker)delegate
			{
				toolStripButtonRecord.Enabled = enable;
			});
		}

		public void toolStripButtonStopEnabled(bool enable)
		{
			Invoke((MethodInvoker)delegate
			{
				toolStripButtonStop.Enabled = enable;
			});
		}

		public void toolStripButtonExportVisible(bool visible)
		{
			if (toolStripButtonExport != null)
			{
				Invoke((MethodInvoker)delegate
				{
					toolStripButtonExport.Visible = visible;
				});
			}
		}
	}
}
